import axios from "axios"
import { Modal } from "view-ui-plus"
const instance = axios.create({
  baseURL: '/api',
  responseType: 'json',
  withCredentials: true, // 是否允许带cookie这些
  headers: {
    'Content-Type': 'application/json;charset=utf-8',
    'x-token': 'jinyue',
  },
  timeout: 3000
})

// 添加请求拦截器
instance.interceptors.request.use(
  function (config) {
    if (config.url === '/user/login') {
      config.headers.token = sessionStorage.getItem('jinyue')
    }
    return config
  },
  function (error) {
    return Promise.reject(error)
  },
)

// 添加响应拦截器
instance.interceptors.response.use(
  function (response) {
    let responseCode = response.status
    if (responseCode === 200) {
      return response.data
    }
    return response
  },
  function (error) {
    return Promise.reject(error)
  },
)


const client = (_url, _method, _jsonValue=null, _param=null, _dst=null)=>{
  instance({
    url: _url,
    method: _method,
    data: _jsonValue,
    params: _param
  }).then((r)=>{
    if (r.statusCode != 0) {
      Modal.warning({
        title: '警告',
        content: r.message + '===>' + r.data,
      })
    } else {
      if(_dst !== null){
        _dst.value.data = r.data
      }

      Modal.success({
        title: '成功',
        content: r.message,
      })
    }
  }).catch((e)=>{
    Modal.error({
      title: '错误!',
      content: e,
    })
  })
}


const doPost = (_url, _jsonValue=null, _dst=null) => {
  client(_url, "POST", _jsonValue,  null, _dst)
}


const doGet = (_url, _params=null, _dst=null) => {
  client(_url, "GET", null, _params, _dst)
}

const doDelete = (_url, _params=null, _dst=null) => {
  client(_url, "DELETE", null, _params, _dst)
}

const doUpdate = (_url, _jsonValue=null, _dst=null) => {
  client(_url, "PUT", _jsonValue,  null, _dst)
}

export {instance, client, doDelete, doGet, doPost, doUpdate}